import { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Modal, Popconfirm, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getUserList, createUser, updateUser, deleteUser } from '@/services/auth/api';
import UserAdd from './UserAdd';
import UserEdit from './UserEdit';
import styles from '@/pages/style.less';

export default () => {
  const tableRef = useRef<ActionType>();
  const [modalAddVisible, setModalAddVisible] = useState(false);
  const [modalEditVisible, setModalEditVisible] = useState(false);
  const [record, setRecord] = useState<API.UserItem>({});
  const [selectedRowId, setSelectedRowId] = useState('');

  const getRowClassName = (rd: API.UserItem) => {
    if ((rd.id as string) === selectedRowId) return styles.selectedRow;
    return '';
  };

  const columns: ProColumns<API.UserItem>[] = [
    {
      title: '姓名',
      dataIndex: 'username',
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      hideInSearch: true,
      renderText: (__, rd) => (rd.sex === 1 ? '男' : '女'),
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, rd) => [
        <Button
          type="primary"
          size="small"
          key="edit"
          onClick={() => {
            setModalEditVisible(true);
            setRecord(rd);
          }}
        >
          修改
        </Button>,
        <Popconfirm
          placement="topRight"
          title="是否删除?"
          okText="Yes"
          cancelText="No"
          key="delete"
          onConfirm={async () => {
            const response = await deleteUser(rd.id as string);
            if (response.code === 10000) message.info(`用户: 【${rd.username}】 删除成功`);
            else message.warn(`用户: 【${rd.username}】 删除失败`);
            tableRef.current?.reload();
          }}
        >
          <Button danger size="small">
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  const addItem = async (values: any) => {
    console.log(values);
    const response = await createUser(values);
    if (response.code !== 10000) {
      message.error('创建用户失败');
    }

    if (response.code === 10000) {
      setModalAddVisible(false);
      tableRef.current?.reload();
      setSelectedRowId(response.data.insert_illuminant_user_one.id);
    }
  };

  const editItem = async (values: any) => {
    values.id = record.id;
    console.log(values);
    const response = await updateUser(values);
    if (response.code !== 10000) {
      message.error('编辑用户失败');
    }

    if (response.code === 10000) {
      setModalEditVisible(false);
      tableRef.current?.reload();
      setSelectedRowId(response.data.update_illuminant_user_by_pk.id);
    }
  };

  return (
    <PageContainer fixedHeader header={{ title: '用户列表' }}>
      <ProTable<API.UserItem>
        columns={columns}
        rowClassName={getRowClassName}
        rowKey="id"
        actionRef={tableRef}
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setModalAddVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params: API.UserItem & API.PageInfo) => {
          const resp = await getUserList(params);
          return {
            data: resp.data.illuminant_user,
            total: resp.data.illuminant_user_aggregate.aggregate.count,
          };
        }}
      />
      <Modal
        destroyOnClose
        title="新增"
        visible={modalAddVisible}
        footer={null}
        onCancel={() => setModalAddVisible(false)}
      >
        <UserAdd onFinish={addItem} />
      </Modal>
      <Modal
        destroyOnClose
        title="编辑"
        visible={modalEditVisible}
        footer={null}
        onCancel={() => setModalEditVisible(false)}
      >
        <UserEdit onFinish={editItem} record={record} />
      </Modal>
    </PageContainer>
  );
};
